package com.xin.chaingeneration.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xin.chaingeneration.common.ResponseEntity;
import com.xin.chaingeneration.entity.NewsCooperative;
import com.xin.chaingeneration.service.NewsCooperativeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/newsCooperative")
public class NewsCooperativeController {

    @Autowired
    NewsCooperativeService newsCooperativeService;

    @PostMapping("/saveNews")
    public ResponseEntity<String> saveNews(@RequestBody List<NewsCooperative> newsCooperatives){

        List<NewsCooperative> newsNotNull = newsCooperatives.stream()
                .filter(item -> item.getContent().length() >= 10)
                .collect(Collectors.toList());

        newsCooperativeService.saveBatch(newsNotNull);

        return ResponseEntity.success("保存成功");
    }

    @GetMapping("/getNewsByProductId/{productId}")
    public ResponseEntity<List<NewsCooperative>> getNewsByProductId(@PathVariable Long productId){
        LambdaQueryWrapper<NewsCooperative> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(NewsCooperative::getProductId,productId);

        List<NewsCooperative> list = newsCooperativeService.list(queryWrapper);

        ResponseEntity<List<NewsCooperative>> responseEntity = ResponseEntity.success(list);
        responseEntity.setCode(1);

        return responseEntity;
    }

    @PostMapping("/updateNews")
    public ResponseEntity<String> updateNews(@RequestBody List<NewsCooperative> news){

        newsCooperativeService.updateBatchById(news);

        return ResponseEntity.success("保存成功");
    }
}
